<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */
declare (strict_types=1);

namespace app\middleware;

use think\App;
use think\facade\Db;
use think\facade\Log;
use think\Response;

class LogBehavior
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 监听SQL
        $method = request()->method();
        if (strtolower($method) !== 'options') {
            // 记录路由和请求信息
            if (config('app.app_debug')) {
                try {
                    Log::record('[ HEADER ] ' . var_export($request->header(), true), 'info');
                    Log::record('[ PARAM ] ' . var_export($request->param(), true), 'info');
                } catch (\Exception $e) {
                    bs_log($e->getMessage(), 'error-log', 'err.log');
                }
            }
            config('database.debug') && Log::record(PHP_EOL, 'sql');
            config('database.debug') && Log::record(request()->method() . ': ' . request()->url(true), 'sql');
        }

        Db::listen(function ($sql, $time, $master) {

            $debug = config('database.debug', true);
            if (!$debug) {
                return;
            }
            if (0 === strpos($sql, 'CONNECT:')) {
                Log::record($sql, 'sql');
                return;
            }
            // 记录SQL
            if (is_bool($master)) {
                // 分布式记录当前操作的主从
                $master = $master ? 'master|' : 'slave|';
            } else {
                $master = '';
            }
            Log::record($sql . ' [ ' . $master . 'RunTime:' . $time . 's ]', 'sql');

            if ($time > 1) {
                bs_log([
                    'sql' => $sql,
                    'time' => $time . 's',
                    'url' => request()->url()
                ], '慢日志', 'sql-slow.log');
            }
        });
        return $next($request);
    }
}
